package cn.wei.youvie.controller;

import cn.wei.youvie.common.annotation.AuthCheck;
import cn.wei.youvie.common.constant.UserConstant;
import cn.wei.youvie.common.exception.BusinessException;
import cn.wei.youvie.common.exception.ThrowUtils;
import cn.wei.youvie.common.servlet.BaseResponse;
import cn.wei.youvie.common.servlet.DeleteRequest;
import cn.wei.youvie.common.servlet.ErrorCode;
import cn.wei.youvie.common.servlet.ResultUtils;
import cn.wei.youvie.domain.dto.book.BookAddRequest;
import cn.wei.youvie.domain.dto.book.BookEditRequest;
import cn.wei.youvie.domain.dto.book.BookQueryRequest;
import cn.wei.youvie.domain.dto.book.BookUpdateRequest;
import cn.wei.youvie.domain.entity.Book;
import cn.wei.youvie.domain.entity.User;
import cn.wei.youvie.domain.vo.BookVO;
import cn.wei.youvie.service.BookService;
import cn.wei.youvie.service.UserService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;

@RestController
@RequestMapping("/book")
@Slf4j
public class BookController {


    @Resource
    private BookService bookService;

    @Resource
    private UserService userService;

    /**
     * 新建书籍
     */
    @PostMapping("/add")
    public BaseResponse<Integer> addBook(@RequestBody BookAddRequest booksAddRequest, HttpServletRequest request) {
        Integer bookId = bookService.add(booksAddRequest, request);
        return ResultUtils.success(bookId);
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteBook(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        boolean removed = bookService.deleteBook(deleteRequest, request);
        return ResultUtils.success(removed);
    }

    /**
     * 更新（仅管理员）
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateBook(@RequestBody BookUpdateRequest booksUpdateRequest) {
        boolean updated = bookService.updateBook(booksUpdateRequest);
        return ResultUtils.success(updated);
    }

    /**
     * 根据 id 获取
     */
    @GetMapping("/get/vo")
    public BaseResponse<BookVO> getBookVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Book book = bookService.getById(id);
        if (book == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(bookService.getBookVO(book, request));
    }

    /**
     * 分页获取列表（仅管理员）
     *
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Book>> listBookByPage(@RequestBody BookQueryRequest booksQueryRequest) {
        long current = booksQueryRequest.getCurrent();
        long size = booksQueryRequest.getPageSize();
        Page<Book> booksPage = bookService.page(new Page<>(current, size),
                bookService.getQueryWrapper(booksQueryRequest));
        return ResultUtils.success(booksPage);
    }

    /**
     * 分页获取列表（封装类）
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<BookVO>> listBookVOByPage(@RequestBody BookQueryRequest booksQueryRequest,
                                                       HttpServletRequest request) {
        return null;
    }

    /**
     * 分页获取当前用户创建的资源列表
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<BookVO>> listMyBookVOByPage(@RequestBody BookQueryRequest booksQueryRequest,
                                                         HttpServletRequest request) {
        if (booksQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        booksQueryRequest.setUserId(loginUser.getId());
        long current = booksQueryRequest.getCurrent();
        long size = booksQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 50, ErrorCode.PARAMS_ERROR);
        Page<Book> bookPage = bookService.page(new Page<>(current, size),
                bookService.getQueryWrapper(booksQueryRequest));
        return ResultUtils.success(bookService.getBookVOPage(bookPage, request));
    }

    /**
     * 分页搜索（从 ES 查询，封装类）
     */
    @PostMapping("/search/page/vo")
    public BaseResponse<Page<BookVO>> searchBookVOByPage(@RequestBody BookQueryRequest booksQueryRequest,
                                                         HttpServletRequest request) {
        /*long size = booksQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Book> booksPage = bookService.searchFromEs(booksQueryRequest);
        return ResultUtils.success(bookService.getBookVOPage(booksPage, request));*/
        return null;
    }

    /**
     * 编辑（用户）
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editBook(@RequestBody BookEditRequest booksEditRequest, HttpServletRequest request) {
        if (booksEditRequest == null || booksEditRequest.getBookId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Book book = new Book();
        BeanUtils.copyProperties(booksEditRequest, book);

        User loginUser = userService.getLoginUser(request);
        long id = booksEditRequest.getBookId();
        // 判断是否存在
        Book oldBook = bookService.getById(id);
        ThrowUtils.throwIf(oldBook == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldBook.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = bookService.updateById(book);
        return ResultUtils.success(result);
    }

    @PostMapping("/insertContentOfFile")
    public BaseResponse<Boolean> handleFileUpload(@RequestParam("file") MultipartFile file,
                                                  @RequestParam("bookId") int bookId,
                                                  HttpServletRequest request) {
        ThrowUtils.throwIf(file.isEmpty(), ErrorCode.PARAMS_ERROR, "未上传文件");

        return ResultUtils.success(bookService.insertContentOfFile(file, request, bookId));
    }

}
